package com.basic.library.base;

import android.app.Activity;
import android.app.Application;
import android.app.Notification;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.StrictMode;
import android.text.TextUtils;

import com.basic.library.BuildConfig;
import com.basic.library.bean.UserInfo;
import com.basic.library.httpmanager.task.ApiHttpService;
import com.basic.library.httpmanager.task.RxEasyHttpConfig;
import com.basic.library.utils.AppUtil;
import com.basic.library.utils.LocalData;
import com.basic.library.utils.MyLog;
import com.basic.library.utils.download.Downloader;
import com.google.gson.Gson;
import com.jeremy.fastsharedpreferences.FastSharedPreferences;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.zhouyou.http.EasyHttp;

import java.util.LinkedList;
import java.util.List;

/**
 * @author jiangyun
 * @description
 * @time 创建时间：2018/3/26 09:59
 */
public abstract class BaseApplication extends Application {
    protected static BaseApplication instance;
    protected Handler handler = new Handler(Looper.getMainLooper());
    protected List<Activity> activityList = new LinkedList<Activity>();

    public static BaseApplication getInstance() {
        return instance;
    }

    /**
     * 配置网络请求的BaseURL
     *
     * @return
     */
    protected abstract String getBaseUrl();

    protected abstract BaseApplication initInstance();

    void initBaseUrl() {
        if (TextUtils.isEmpty(getBaseUrl()))
            throw new NullPointerException("ApiService.BASE_URL不能为空,需在重写getBaseUrl()方法中初始化~~");
        ApiHttpService.BASE_URL = getBaseUrl();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = initInstance();
        if (instance == null)
            throw new NullPointerException("initInstance()需初始化~~");
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        String processName = AppUtil.getProcessName(this);
        if (!TextUtils.equals(getPackageName(), processName)) return;
        initBili();
        EasyHttp.init(this);
        FastSharedPreferences.init(this);
        LiveEventBus
                .config()
                .lifecycleObserverAlwaysActive(true)
                .enableLogger(BuildConfig.DEBUG)
                .autoClear(false); //消息总线
        initBaseUrl();
        RxEasyHttpConfig.initConfig(); //RxEasy配置
        Downloader.getInstance().init(this); //多进程中有问题？
        initInMainProcess();
    }

    protected abstract void initInMainProcess();

    public void initBili() {
//        IBoxingMediaLoader loader = new BoxingGlideLoader();
//        BoxingMediaLoader.getInstance().init(loader);
//        BoxingCrop.getInstance().init(new BoxingUcrop());//如果你需要裁剪功能的话。
    }

    public Activity getActivityLast() {
        return activityList.get(activityList.size() - 1);
    }

    public void removeActivity(Activity activity) {
        activityList.remove(activity);
    }

    public void addActivity(Activity activity) {
        activityList.add(activity);
    }

    public void exit() {
        for (int i = 0; i < activityList.size(); i++) {
            Activity activity = activityList.get(i);
            activity.finish();
            activityList.remove(activity);
            --i;
        }
        activityList.clear();
        // android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    //连续关闭几个activity
    public void finish(int num) {
        for (int i = 1; i <= num; i++) {
            activityList.get(activityList.size() - i).finish();
        }
    }

    //关闭指定activity
    public void finish(String className) {
        for (Activity activity : activityList) {
            if (activity.getClass().getName().equals(className)) {
                activity.finish();
            }
        }
    }

    private long lastClickTime = 0;

    //重新登录,清除所有信息
    public void reLogin() {
        handler.post(() -> {
            long time = System.currentTimeMillis();
            if (time - lastClickTime < 600) return;
            lastClickTime = time;
            UserInfo info = new UserInfo();
            info.setMobile(LocalData.getInstance().getUserInfo().getMobile());
            LocalData.getInstance().setUserInfo(info);

            List<Activity> list = new LinkedList<>(activityList);
            activityList.clear();

            Intent intent = new Intent();
            intent.setClassName(getPackageName(), "com.tz.qy.qypostsale.ui.login.LoginActivity");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);

            for (Activity activity : list) {
                if (!activity.isFinishing() && !activity.isDestroyed())
                    activity.finish();
            }
            MyLog.p("重新登录：" + new Gson().toJson(LocalData.getInstance().getUserInfo()));
            try {
                Notification.Builder builder = new Notification.Builder(this);
                builder.setAutoCancel(true)
                        .setVisibility(Notification.VISIBILITY_SECRET);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}
